package com.wwdx.wechat.handler;

import com.google.common.collect.Lists;
import com.wwdx.model.WwdxWeixinUserModel;
import com.wwdx.model.dto.BaseActivityDTO;
import com.wwdx.service.impl.BaseWxService;
import com.wwdx.utils.ConstantHolder;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liguoliang
 */
public abstract class AbstractSubscribeHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        BaseWxService service = (BaseWxService) wxMpService;
        String openId = wxMessage.getFromUser();
        logger.info("新关注用户 OPENID: {}" , openId);
        //获取微信用户基本信息
        WxMpUser wxMpUser = service.getUserService().userInfo(openId);
        Integer sex = wxMpUser.getSex();
        Long subscribeTime = wxMpUser.getSubscribeTime();
        String city = wxMpUser.getCity(),country = wxMpUser.getCountry(),province = wxMpUser.getProvince(),
                unionId = wxMpUser.getUnionId(),appId = service.getWxMpConfigStorage().getAppId(),
                nickname = wxMpUser.getNickname(),headImgUrl = wxMpUser.getHeadImgUrl();
        WwdxWeixinUserModel wwdxWeixinUserModel = wwdxWeixinUserService.getByOpenId(openId);
        if (wwdxWeixinUserModel == null){
            wwdxWeixinUserModel = WwdxWeixinUserModel.builder()
                    .openid(openId).appid(appId).unionid(unionId).nickname(nickname).sex(sex).headimgurl(headImgUrl)
                    .city(city).country(country).province(province).language(wxMpUser.getLanguage()).subscribe(Boolean.TRUE)
                    .subscribeTime(subscribeTime).gmtCreated(new Date()).gmtModified(new Date()).build();
            wwdxWeixinUserService.save(wwdxWeixinUserModel);
        }
        //订阅页新关注用户默认订阅
        String eventKey = wxMessage.getEventKey();
        if (StringUtils.isNotBlank(eventKey)){
            //渠道二维码票据
            String channelSources = StringUtils.substringAfter(eventKey, "_");
            String subscribe = "subscribe";
            if (subscribe.equalsIgnoreCase(channelSources)){
                //新增用户
                String date = new LocalDate().toString();
                String subscribeNewKey = String.format(ConstantHolder.USER_SUBSCRIBE_NEW_SET, date);
                setOperations.add(subscribeNewKey,unionId);
                redisTemplate.expire(subscribeNewKey,30 * 60 * 60 , TimeUnit.SECONDS);
                setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionId);
            }
        }
        //发送客服消息
        this.sendKefuMessage(openId,service);
        //赠一得一未关注通知
        taskExecutor.execute(()->{
            Boolean member = hashOperations.hasKey(ConstantHolder.GIVEONE_UNIONID_MAP, unionId);
            if (member){
                BaseActivityDTO.GiveOneBusinessDTO dto = (BaseActivityDTO.GiveOneBusinessDTO) hashOperations.get(ConstantHolder.GIVEONE_UNIONID_MAP, unionId);
                Long bookid = dto.getBookid();
                //保存赠一得一订单
                if (dto.getBookFlag().equalsIgnoreCase(bookid.toString())){
                    payService.executeGiveoneOrder(dto);
                }
                hashOperations.delete(ConstantHolder.GIVEONE_UNIONID_MAP,unionId);
            }
        });
        return null;
    }

    private void sendKefuMessage(String openid,BaseWxService service) throws WxErrorException{
        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
        WxMpUser wxMpUser = service.getUserService().userInfo(openid);
        String url="http://mmbiz.qpic.cn/mmbiz_png/G8V8d8SnNEPo2icxhdPzAAB1992zYkv26HvpPYtKZ0RXFMo0oS0MtgibcVGlz9a6QWaEtMtntssicIBeSu1U6N9VA/0?wx_fmt=png";
        article.setPicUrl(url);
        article.setDescription("@"+wxMpUser.getNickname()+"！欢迎来到蜜读听书，以帮助100多万听书用户奉献知识精华，点击免费领书。");
        article.setUrl(wechatUrl+"auth.html");
        List<WxMpKefuMessage.WxArticle> articles = Lists.newArrayList(article);
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setToUser(openid);
        message.setMsgType(WxConsts.XmlMsgType.NEWS);
        message.setArticles(articles);
        service.getKefuService().sendKefuMessage(message);
    }
}